package com.bnz.security.controller;

import com.bnz.security.entity.R;
import com.bnz.security.entity.Users;
import com.bnz.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public R index(){
        //1.1 获取登录名
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        //1.2 输出登录名
        return R.ok().data("name",name);
    }

    @RequestMapping("/success")
    public String success(){
        return "success";
    }

    //3. 查询所有用户
    @GetMapping("/user/findAll")
    //@Secured("ROLE_user")                   //判断是否有指定的角色
    @PreAuthorize("hasAuthority('admin')")  //方法前授权：判断是否有指定的权限
    //@PostAuthorize("hasAuthority('admin')")   //方法后授权:方法体语句会执行
    @PostFilter("filterObject.username == '张三'")
    public List<Users> findAll(){
        List<Users> users = userService.findAll();
        //System.out.println("users = " + users);     //方法后授权会打印此句，方法前不会
        return users;
    }

}
